package com.pajk.user.service.login;


import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;



import com.alibaba.common.lang.StringUtil;
import com.pajk.user.ExceptionCode;
import com.pajk.user.api.LoginService;
import com.pajk.user.dal.index.TairIndex;
import com.pajk.user.dal.mapper.UserMapper;
import com.pajk.user.exception.UserServiceException;
import com.pajk.user.model.User;

public class LoginServiceImpl implements LoginService{
	
	private static final Logger Log = LoggerFactory.getLogger(LoginServiceImpl.class);
	
	@Resource
    private TairIndex<Long, Long> mobileToUserIdIndex;
	
    @Resource
    private UserMapper userMapper;

	@Override
	public Long login(Long mobile, String password) {
		if(mobile == null || StringUtil.isEmpty(password)) {
			throw new IllegalArgumentException("mobile or password cannot be null!");
    	}
    	try {
	        // 1. mobile --> user id
	        Long userId = mobileToUserIdIndex.get(mobile);
	        if(userId == null) {
	        	Log.error("userId cannot found in tair, userId is {}", userId);
	    		return null;
	        }
	        // 2. check password
	        User user = userMapper.getUserById(userId);
	        if(user == null) {
	        	Log.error("user cannot found, userId is {}", userId);
	    		return null;
	        }else if(!password.equals(user.getPassword())) {
	        	Log.error("password error");
	        	return null;
	        }
	        
	        return userId;
    	}catch(UserServiceException e){
            Log.error("LoginServiceException catched.", e);
            throw e;
        }catch(RuntimeException re){
            Log.error("RuntimeException catched.", re);
            throw new UserServiceException(re, ExceptionCode.InternalSystemErrorException.getCode());
        }catch(Throwable t){
            Log.error("Throwable catched.", t);
            throw new UserServiceException(t, ExceptionCode.InternalSystemErrorException.getCode());
        }
	}

	@Override
	public void invalidateSession(Long userId, Long operatorId, Long vendorId) {
		// TODO Auto-generated method stub
		
	}

}
